package com.qf.service.impl;

import com.qf.dao.AddressDao;
import com.qf.dao.CartDao;
import com.qf.dao.UserDao;
import com.qf.dao.impl.AddressDaoImpl;
import com.qf.dao.impl.CartDaoImpl;
import com.qf.dao.impl.UserDapImpl;
import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.util.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Administrator
 * @version v1.0
 * @date 2022/4/18
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDapImpl();
    @Override
    public boolean checkUsername(String username) {
       long count= userDao.selectCountByUsername(username);
       if(count>0){
           return true;
       }
        return false;
    }

    @Override
    public boolean register(String username, String password, String email, String gender) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setGender(gender);
        user.setEmail(email);
        user.setFlag(1);
        int count = userDao.insert(user);
        return count==1;
    }

    @Override
    public User login(String username, String password) {
        return userDao.selectByUsernameAndPassword(username,password);
    }

    @Override
    public List<User> selectUsers() {
        return userDao.selectUsers();
    }
    AddressDao addressDao = new AddressDaoImpl();
    CartDao cartDao = new CartDaoImpl();
    @Override
    public List<User> deleteUser(int id) {

        try {
            DataSourceUtils.begin();
            long count = addressDao.findCountByUid(id);
            long size = cartDao.findCountByUid(id);
            List<User> list=null;
            if(count==0||size==0){
                userDao.deleteUser(id);
                 list  = userDao.selectUsers();
            }else{
                System.out.println("不能删除");
            }

            DataSourceUtils.commit();
            return list;
        } catch (SQLException e) {
            try {
                DataSourceUtils.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                DataSourceUtils.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return null;

    }

    @Override
    public List<User> findUsersAny(String toString, List<Object> params) {
        return userDao.selectUsersAny(toString,params);
    }


}
